package com.example.administrator.pomelostreet.fragment;


import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.example.administrator.pomelostreet.R;
import com.example.administrator.pomelostreet.tata.ParseJson;
import com.example.administrator.pomelostreet.tata.RecycleViewAdapter;
import com.example.administrator.pomelostreet.tatajavabean.recommend_forums;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class TaTa_Fragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{


    private String url="http://circle.seeyouyima.c" +
            "om/mode_community?platform=android" +
            "&v=2.1.0&devic" +
            "e_id=99000505809169&time=2017-02-06+" +
            "13%3A35%3A34&mode=0&direction=next";


    private Context context;
    private RecyclerView mRecycler;
    private RecycleViewAdapter adapter;

    private SwipeRefreshLayout swipeRefreshLayout;


    private  List<recommend_forums> list = new ArrayList<>();


    public TaTa_Fragment(Context context){
        this.context=context;
    }



    //把数据传到主线程
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String json = (String) msg.obj;
                    ParseJson(json);
                    adapter = new RecycleViewAdapter(context,list);
                    mRecycler.setAdapter(adapter);
                    break;
            }
        }
    };




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_ta_ta_, container, false);

    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        super.onViewCreated(view, savedInstanceState);

        Toolbar toolbar= (Toolbar) view.findViewById(R.id.tool_bar);
        //标题栏上的按钮
        RadioGroup radioGroup= (RadioGroup) view.findViewById(R.id.rg_title);
        RadioButton radioButton0= (RadioButton) view.findViewById(R.id.rb_recommend);
        RadioButton radioButton1= (RadioButton) view.findViewById(R.id.rb_classify);
        RadioButton radioButton2= (RadioButton) view.findViewById(R.id.rb_kong);
        //第一个item的控件
        TextView textView1= (TextView) view.findViewById(R.id.tv_title);
        ImageView imageView1= (ImageView) view.findViewById(R.id.iv_titile1);
        ImageView imageView2= (ImageView) view.findViewById(R.id.iv_titile2);
        ImageView imageView3= (ImageView) view.findViewById(R.id.iv_titile3);
        //第二个item的控件
        TextView textView2= (TextView) view.findViewById(R.id.tv_title2);
        ImageView imageView4= (ImageView) view.findViewById(R.id.iv_titile4);

        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefresh);

        mRecycler = (RecyclerView) view.findViewById(R.id.recycler_view);


        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark);
        swipeRefreshLayout.setOnRefreshListener(this);

        toolbar.setNavigationIcon(R.drawable.apk_mine_fankui);

        toolbar.setTitle("");
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setSubtitle("");
        toolbar.setSubtitleTextColor(Color.WHITE);

        //显示正在加载的进度条
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        });

            //下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){
            @Override
            public void onRefresh() {
                loadData(url);
                adapter.notifyDataSetChanged();
                swipeRefreshLayout.setRefreshing(false);
            }
        });

        //上拉加载
        mRecycler.addOnScrollListener(new RecyclerView.OnScrollListener(){

           int item;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&item+1==adapter.getItemCount()){
                    Adddata();
                }
            }


            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager = mRecycler.getLayoutManager();
                if(layoutManager instanceof LinearLayoutManager){
                    int last=((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                    if(last!=1){
                        item=last;
                    }
                }

            }
        });



        invit(mRecycler);
        loadData(url);


    }
    private void invit(RecyclerView mRecycler){
        //布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycler.setLayoutManager(layoutManager);
    }

      //网络加载数据
    private  void loadData(final String url){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder().url(url).get().build();
                try {
                    Response response = okHttpClient.newCall(request).execute();

                    if (response.isSuccessful()) {
                        String json = response.body().string();
                        Log.i("AAA", "run:+"+json);
                        Message msg = Message.obtain();
                        msg.what = 0;
                        msg.obj = json;
                        handler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void ParseJson(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArray = jsonObject.getJSONArray("recommend_forums");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                recommend_forums recommend = new recommend_forums();
                recommend.setId(jsonObject1.getInt("id"));
                recommend.setName(jsonObject1.getString("name"));
                recommend.setIcon(jsonObject1.getString("icon"));
                recommend.setIcon2(jsonObject1.getString("icon2"));
                recommend.setIcon3(jsonObject1.getString("icon3"));
                list.add(recommend);
            }

        }catch (JSONException e) {
            e.printStackTrace();
        }
    }



    //上拉加载
    public void Adddata() {

        loadData(url);
    }

    @Override
    public void onRefresh() {

    }
}
